import { Component, OnInit } from '@angular/core';
import {FormGroup, FormBuilder, Validators} from "@angular/forms";
import {Router, ActivatedRoute} from "@angular/router";
import {PageSubject} from "../../../../util/page-subject";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {ResponseUtil} from "../../../../util/response-util";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {MsgResult} from "../../../../models/msg-result";
import {MsgConstants} from "../../../../constants/constants";
import {DataStorageUtil} from "../../../../util/data-storage-util";
import {LogUtil} from "../../../../util/log-util";
import {TreeUtil} from "../../../../util/tree-util";
import {SiteManage} from "../site-manage";
import {SiteManageService} from "../site-manage.service";
import {DataDictionaryService} from '../../../../services/dataDictionary.service';

declare  var $;

@Component({
  selector: 'app-site-manage-update',
  templateUrl: './site-manage-update.component.html',
  styleUrls: ['./site-manage-update.component.css']
})
export class SiteManageUpdateComponent implements OnInit {

  site :SiteManage;

  categorys : object;

  siteForm : FormGroup;

  selectGov : string;

  // 所有行政区划数据
  regionsArr: Array<any> = [];
  govOrEnt:string;
  govOrCompany : Array<any> = [];

  regionCode = '';

  // 数据字典中获取数据的编码
  dicPolluteType = 'ZDLEWRY';
  dicPolluteArr: Array<any> = [];


  constructor(
    private router :Router,
    private route :ActivatedRoute,
    private pageSubject : PageSubject,
    private fb : FormBuilder,
    private logUtil :LogUtil ,
    private dialogService :OneDialogService,
    private treeUtil : TreeUtil,
    private responseUtil : ResponseUtil,
    private dataStorageUtil : DataStorageUtil,
    private dicService: DataDictionaryService,
    private sitesService : SiteManageService
  ) {
    this.initObject();
  }


  ngOnInit() {
    this.pushPage();
    this.getDicPolluteType();
    // this.administrativeDivisionTree();
    this.initSiteUpdateForm();
    this.getGovInfos("");
  }

  /**
   * 面包屑
   */
  private pushPage(){
    let path =new Path("运维管理","");
    this.pageSubject.pushPage("站点管理","修改",path);
  }

  /**
   * 构造表单
   */
  private buildForm():void{
    this.siteForm=this.fb.group({
      'id': [this.site.id],
      'siteName': [this.site.siteName,[
        Validators.required,
        Validators.maxLength(50)
      ]],
      'address': [this.site.address,[
        Validators.required,
        Validators.maxLength(50)
      ]],
      'regionCode': [this.site.regionCode,[
        // Validators.required,
        Validators.maxLength(50)
      ]],
      'regionName': [!this.site.regionName ? "" : this.site.regionName],
      'orgId': [!this.site.orgId ? "" : this.site.orgId],
      'orgName': [!this.site.orgName ? "" : this.site.orgName],
      'linkMan': [this.site.linkMan,[
        Validators.maxLength(25)
      ]],
      'contactTel': [this.site.contactTel,[
        Validators.maxLength(14),
        Validators.pattern(/(^(((13[0-9]{1})|(15[0-9]{1}))+\d{8})$)|(^\d{3,4}-?\d{7,9}$)/)
      ]],
      'siteTypeCode': [this.site.siteTypeCode || '',[
        Validators.required,
        Validators.maxLength(3)
      ]],
      'orgType': [this.site.orgType = "1",[
        Validators.required,
        Validators.maxLength(1)
      ]],
      'isUse': [this.site.isUse = "0",[
        Validators.required,
        Validators.maxLength(1)
      ]],
      'isThied': [this.site.isThied = "0" ,[
        Validators.required,
        Validators.maxLength(1)
      ]],
      'isMove': [this.site.isMove = "0" ,[
        Validators.required,
        Validators.maxLength(1)
      ]]

    });

    this.siteForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }

  private onValueChanged(data ?: any) {
    if (!this.siteForm) {
      return;
    }
    const form = this.siteForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  /**
   * 校验字段
   * @type {{name: string; code: string}}
   */
  formErrors = {
    'siteName': '',
    'address': '',
    'regionCode': '',
    'linkMan': '',
    'studyRegionCode': '',
    'studySiteCode': '',
    'contactTel': '',
    'siteTypeCode': '',
    'orgType': '',
    'isUse': '',
    'isThied': '',
    'isMove': '',
  };

  /**
   * 校验提示信息
   * @type {{name: {required: string; maxlength: string}; code: {required: string; maxlength: string; pattern: string}}}
   */
  validationMessages = {
    'siteName': {
      'required': '站点名不能为空',
      'maxlength': '长度不能超过50'
    },
    'address': {
      'required': '站点地址不能为空',
      'maxlength': '长度不能超过50'
    },
    'regionCode': {
      'required': '行政区划不能为空',
      'maxlength': '长度不能超过50'
    },
    'linkMan': {
      'maxlength': '长度不能超过25位',
    },
    'studyRegionCode': {
      'maxlength': '长度不能超过25位',
    },
    'studySiteCode': {
      'maxlength': '长度不能超过50位',
    },
    'contactTel': {
      'maxlength': '长度不能超过14位',
      'pattern':'请填写正确的格式'
    },
    'siteTypeCode': {
      'required': '站点类型不能为空',
      'maxlength': '长度不能超过3位',
    },
    'orgType': {
      'maxlength': '长度不能超过1位',
    },
    'isUse': {
      'maxlength': '长度不能超过1位',
    },
    'isThied': {
      'maxlength': '长度不能超过1位',
    },
    'isMove': {
      'maxlength': '长度不能超过1位',
    }
  };

  /**
   * 初始化对象
   */
  initObject() {
    this.site = new SiteManage();
    this.buildForm();
  }

  /**
   * 站点修改初始化
   */
  initSiteUpdateForm(){
    let id=this.route.snapshot.params['siteId'];
    if(!!id){
      this.sitesService.getSiteById(id).subscribe(
        result =>this.responseUtil.success(result ,this.processSiteByIdResult),
        error => this.responseUtil.error(error)
      );
    }else{
      this.logUtil.debug("修改id为空！");
    }
  }

  /**
   *  初始化站点数据
   * @param result
   */
  processSiteByIdResult= (result : MsgResult) =>{
    if(result && result.code == MsgConstants.MSG_CODE_OK){
      this.site= JSON.parse(JSON.stringify(result.data));
      this.site.regionCode = '';
      this.site.orgName = (result.data.entName = "" ?  "" : (!result.data.entName ? result.data.govName : result.data.entName));
      this.siteForm.patchValue(this.site);
      this.regionCode = result.data.regionCode;
      this.getRegionsTree();
      this.initSiteCategory();
    }
    if(result && result.code != MsgConstants.MSG_CODE_OK){
      this.dialogService.info(result.message);
    }
  }

  /**
   * 初始化站点类型
   */
  initSiteCategory(){
    this.sitesService.getSiteCategoryInfos().subscribe(
      result =>this.responseUtil.success(result ,this.processSiteCategoryResult),
      error => this.responseUtil.error(error)
    );
  }

  private processSiteCategoryResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      result.data.forEach( (val) => {
        this.dicPolluteArr.every((dic) => {
          if (val.monitorCategory === dic.value) {
            val.cateName = dic.display;
            return false;
          } else {
            return true;
          }
        })
      });
      this.categorys = result.data;
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 初始行政区划
   */
  getParentRegion(regionCode){
    this.sitesService.getParentRegion(regionCode).subscribe(
      result =>this.responseUtil.success(result ,() => {
        if (result.data && result.data.length > 0) {
          this.site.regionCode = result.data.join(' / ');
          this.siteForm.patchValue(this.site)
        }
        console.log(result.data);
      }),
      error => this.responseUtil.error(error)
    );
  }



  onSubmit(){
    this.site=this.siteForm.value;
    const regionArr = this.site.regionCode;
    if (Array.isArray(regionArr)) {
      this.site.regionCode = regionArr[regionArr.length - 1];
    } else {
      this.site.regionCode = this.regionCode;
    }
    this.sitesService.updateSite(this.site).subscribe(
      result =>this.responseUtil.success(result ,this.processSiteResult),
      error => this.responseUtil.error(error)
    );
  }

  private processSiteResult= (result : MsgResult) => {
    if(result && result.code == MsgConstants.MSG_CODE_OK){
      this.cancelSiteUpdate();
    }
    if(result && result.code != MsgConstants.MSG_CODE_OK){
      this.dialogService.info(result.message);
    }
  };

  cancelSiteUpdate(){
    this.router.navigate(['..'],{relativeTo :this.route});
  }


  /**
   * 获取行政区划树
   */
  administrativeDivisionTree() {
    let regionCode = "0";
    this.sitesService.getRetrieveRegionsTree(regionCode).subscribe(
      result => this.responseUtil.success(result, this.processRegionsTreeResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 对行政区划树结果处理
   * @param result
   */
  private processRegionsTreeResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.regioCodezTree(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   *  行政区划树
   */
  private regioCodezTree(datasTree) {
    let datas = datasTree || [];
    // 新增中的树
    let userUpdateZtreeSetting = {
      view: {
        fontCss: this.setFontCss_ztree //设置字体颜色
      },
      callback: {
        onClick: this.userUpdateZtreeClick
      }
    };
    $.fn.zTree.init($("#user_update_orgTree"), userUpdateZtreeSetting, datas);
  }

  //同步到文本框
  userUpdateZtreeClick = (even, id, treeNode) => {
    this.site = this.siteForm.value;
    this.site.regionCode = treeNode.id;
    this.site.regionName = treeNode.name;
    this.site.orgId = "";
    this.site.orgName = "";
    this.siteForm.setValue(this.site);
  }

  /**
   * 搜索节点，并展开
   */
  enterSearch() {
    let inputValue = $("#serach_regionName").val();
    let treeId = "user_update_orgTree";
    this.treeUtil.searchTreeNode(treeId, inputValue);
  }

  /**
   * 设置树节点字体样式
   */
  private  setFontCss_ztree(treeId, treeNode){
    if (treeNode.id == 0) {
      //根节点
      return {color: "#333", "font-weight": "bold"};
    } else if (treeNode.isParent == false) {
      //叶子节点
      return (!!treeNode.highlight) ? {color: "#48ab5d", "font-weight": "bold"} : {
        color: "#333",
        "font-weight": "normal"
      };
    } else {
      //父节点
      return (!!treeNode.highlight) ? {color: "#48ab5d", "font-weight": "bold"} : {
        color: "#333",
        "font-weight": "normal"
      };
    }
  }

  /**
   * 选择企业或政府
   * @param elem
   */
  entOrGovChange = (elem) => {
    console.log(elem);
    let params= elem.value;
    if (elem.value == "1" ) {
      this.getGovInfos('');
    }
    if (elem.value == "2") {
      this.getEntInfos('');
    }
  }

  /**
   *  回车查询
   */
  searchGovOrEnt(){
    let elem= $("#org_type").val();
    this.entOrGovChange(elem);
  }

  /**
   * 查询政府信息
   * @param param
   */
  getGovInfos(param :string){
    this.sitesService.getGovInfos(param).subscribe(
      result => this.responseUtil.success(result, this.processGovResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 处理政府结果
   * @param result
   */
  private processGovResult= (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.length > 0) {
        this.govOrCompany = result.data;
      }
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 查询企业信息
   * @param param
   */
  getEntInfos(param :string){
    this.sitesService.getEntInfos(param).subscribe(
      result => this.responseUtil.success(result, this.processEntResult),
      message => this.responseUtil.error(message)
    );
  }

  private processEntResult= (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.length > 0) {
        this.govOrCompany = result.data;
      }
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 同步数据到文本框
   * @param info
   */
  govOrcompanyInfo(info){
    this.site = this.siteForm.value;
    this.site.orgId = info.id;
    this.site.orgName = info.name;
    this.siteForm.setValue(this.site);
  }


  /**
   * 获取行政区划树
   */
  getRegionsTree () {
    this.sitesService.getRetrieveRegionsTree('0').subscribe(
      result => this.responseUtil.success(result,  () => {
        if (result && result.code === MsgConstants.MSG_CODE_OK) {
          this.regionsArr = result.data.children;
          this.getParentRegion(this.regionCode);
        }
        if (result && result.code !== MsgConstants.MSG_CODE_OK) {
          this.dialogService.info(result.message);
        }
      }),
      error => this.responseUtil.error(error)
    );
  }
  /**
   * 获取数据字典中站点类型-大类
   */
  getDicPolluteType () {
    this.dicService.getChildDicByCode(this.dicPolluteType).subscribe(
      result => this.responseUtil.success(result,  () => {
        if (result && result.code === MsgConstants.MSG_CODE_OK) {
          if (result.data.length > 0) {
            this.dicPolluteArr = result.data;
            this.initSiteCategory();
          }
        }
        if (result && result.code !== MsgConstants.MSG_CODE_OK) {
          this.dialogService.info(result.message);
        }
      }),
      error => this.responseUtil.error(error)
    );
  }
}
